package com.sanyue.codingsettlement.service.impl;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanyue.codingsettlement.common.ErrorCode;
import com.sanyue.codingsettlement.constant.CommonConstant;
import com.sanyue.codingsettlement.exception.BusinessException;
import com.sanyue.codingsettlement.exception.ThrowUtils;
import com.sanyue.codingsettlement.mapper.ChartMapper;
import com.sanyue.codingsettlement.model.dto.chart.ChartQueryRequest;
import com.sanyue.codingsettlement.model.entity.Chart;
import com.sanyue.codingsettlement.model.entity.User;
import com.sanyue.codingsettlement.model.enums.FileUploadBizEnum;
import com.sanyue.codingsettlement.model.vo.ChartVO;
import com.sanyue.codingsettlement.model.vo.UserVO;
import com.sanyue.codingsettlement.service.ChartService;
import com.sanyue.codingsettlement.service.UserService;
import com.sanyue.codingsettlement.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * 用户队伍关联表服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart> implements ChartService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param chart
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validChart(Chart chart, boolean add) {
        String name = chart.getName();
        String goal = chart.getGoal();
        String chartData = chart.getChartData();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(name), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(chartData), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(name)) {
            ThrowUtils.throwIf(name.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param chartQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {

        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = chartQueryRequest.getId();
        String searchText = chartQueryRequest.getSearchText();
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String status = chartQueryRequest.getStatus();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", name).or().like("goal", goal));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(goal), "goal", goal);
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(chartType), "chartType", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取用户队伍关联表封装
     *
     * @param chart
     * @param request
     * @return
     */
    @Override
    public ChartVO getChartVO(Chart chart, HttpServletRequest request) {
        // 对象转封装类
        ChartVO chartVO = ChartVO.objToVo(chart);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = chart.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        chartVO.setUserVO(userVO);
        // 2. 已登录，获取用户点赞、收藏状态
        long chartId = chart.getId();
        User loginUser = userService.getLoginUserPermitNull(request);
        // endregion

        return chartVO;
    }

    /**
     * 分页获取用户队伍关联表封装
     *
     * @param chartPage
     * @param request
     * @return
     */
    @Override
    public Page<ChartVO> getChartVOPage(Page<Chart> chartPage, HttpServletRequest request) {
        List<Chart> chartList = chartPage.getRecords();
        Page<ChartVO> chartVOPage = new Page<>(chartPage.getCurrent(), chartPage.getSize(), chartPage.getTotal());
        if (CollUtil.isEmpty(chartList)) {
            return chartVOPage;
        }
        // 对象列表 => 封装对象列表
        List<ChartVO> chartVOList = chartList.stream().map(chart -> {
            return ChartVO.objToVo(chart);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = chartList.stream().map(Chart::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态
        Map<Long, Boolean> chartIdHasThumbMap = new HashMap<>();
        Map<Long, Boolean> chartIdHasFavourMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        // 填充信息
        chartVOList.forEach(chartVO -> {
            Long userId = chartVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            chartVO.setUserVO(userService.getUserVO(user));
        });
        // endregion

        chartVOPage.setRecords(chartVOList);
        return chartVOPage;
    }


}
